import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'main.dart';

class ValueNotifierPage extends StatefulWidget {
  @override
  ValueNotifierPageState createState() => new ValueNotifierPageState();
}

class ValueNotifierPageState extends State<ValueNotifierPage> {
  ValueNotifier<int> _valueNotifier = ValueNotifier(0);
  UserNotifier _userNotifier = UserNotifier(UserInfo('',20));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(''),
      ),
      body: ValueListenableBuilder<UserInfo>(
        valueListenable: _userNotifier,
        builder: (context, value, child) {
          return Column(
            children: [
              ElevatedButton(
                onPressed: (){testUserFunction();},
                child: Text('加加加'),
                style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.all(Colors.blueGrey)),
              ),
              ElevatedButton(
                child: Text("姓名是：${value.name}  年龄是: ${value.age}",style: TextStyle(color: Colors.white),),
                style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.all(Colors.blue)),
              ),
            ],
          );
        },
      ),
    );
  }
  void testUserFunction() {
    _userNotifier.setName("李四");
    _userNotifier.setAge(40);
  }

  void push(Widget widget) {
    Navigator.push(context, MaterialPageRoute(builder: (context) => widget));
    //Navigator.of(context).popUntil((route) => false);//删除所有路由
  }

  @override
  void initState() {
    super.initState();
  }
}

///自定义ValueNotifier
class UserNotifier extends ValueNotifier<UserInfo> {
  UserNotifier(UserInfo value) : super(value);

  void setName(String name) {
    value.name = name;

    ///通知更新
    notifyListeners();
  }
  void setAge(int age) {
    value.age = age;
    ///通知更新
    notifyListeners();
  }
}

///实际中变量可能足够的多
class UserInfo {
  UserInfo(this.name, this.age);

  String name;
  int age;
}
